package com.qiall.boot.userservice.Impl.login;

import com.alibaba.fastjson.JSON;
import com.qiall.boot.cache.ability.service.CacheService;
import com.qiall.boot.userservice.data.mapper.UserMapper;
import com.qiall.common.exception.BusinessException;
import com.qiall.common.exception.ResultCode;
import com.qiall.datautil.Md5Util;
import com.qiall.datautil.PassiveExpiringMapUtil;
import com.qiall.datautil.RandomUtil;
import com.qiall.user.ability.entity.*;
import com.qiall.user.ability.service.login.AuthTwoLoginService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import com.qiall.boot.userservice.data.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.qiall.assertutil.Assert;

@Component
@DubboService
public class AuthTwoLoginServiceImpl implements AuthTwoLoginService {

   private PassiveExpiringMapUtil signCache = new PassiveExpiringMapUtil();

    @Autowired
    private UserMapper userMapper;

    @DubboReference
    private CacheService cacheService;

    @Value("${user.info.redis.expire}")
    private Integer expire;

    @Override
    public SignDTO getSign(GetSignDTO getSignDTO) {

        String account = getSignDTO.getAccount();
        UserInfo userInfo = userMapper.selectByAccount(account);
        Assert.notNull(userInfo);
        String date = getSignDTO.getDate();
        String md5Hex = getSign(date, account);
        SignDTO signDTO = new SignDTO(md5Hex);
        signCache.put(account, account+getSignDTO.getDate());
        return signDTO;
    }

    // * 2. 签名+时间(yyyy-MM-dd hh:MM:ss)+account+password md5 调用 auth 接口获取到accessToken
    private static String getSign(String var1, String var2) {
        String sign = var1 + var2;
        return Md5Util.md5(sign);
    }


    @Override
    public IsAuthSuccessDTO auth(AuthDTO authDTO) {
        UserInfo userInfo = userMapper.selectByAccount(authDTO.getAccount());
        if(userInfo==null){
            throw new BusinessException(ResultCode.USER_NOT_EXIT,"用户不存在");
        }
        String var1=signCache.get(authDTO.getAccount());
        String signServer = getSign(var1,userInfo.getUserPassword());
        if(!signServer.equals(authDTO.getSignWithPassword())){
            throw new BusinessException(ResultCode.PARAM_IS_INVALID,"校验失败签名错误");
        }
       String token= RandomUtil.randomString(64);
        IsAuthSuccessDTO  isAuthSuccessDTO=new IsAuthSuccessDTO();
        isAuthSuccessDTO.setAccessToken(token);
        isAuthSuccessDTO.setUserId(userInfo.getId());
        cacheService.setValue(DataBuildUtil.buildAccessToken(token), JSON.toJSONString(userInfo),expire);
        return isAuthSuccessDTO;
    }

}
